<template>
  <!-- ShapeGeometry可以用来创建自定义的二维图形.
实际上ShapeGeometry创建图形必须要用到基类Shape，观察它的原型链： 
Shape类继承自Path类，Path类由继承自CurvePath类，我们用来画图的方法实际都是从CurvePath继承来的，
CurvePath继承自Curve类，Curve类又继承自Object类，果然一切皆对象啊，
通过从Path继承来的方法进行绘制，继承自Curve类的getPoints和getSpacedPoints方法可以获取路径points-->
  <div class="shape-geometry">
    <div id="scene"></div>
    <div class="controls-box">
      <section>
        <el-row>
          <el-col :span="8" class="label-col"><label>drawType</label></el-col>
          <el-col :span="16">
            <el-select v-model="drawType" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </section>
    </div>
  </div>
</template>

<script>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

let scene;
let camera;
let renderer;
let controls;
export default {
  data() {
    return {
      options: [
        {
          value: "asGeom",
          label: "asGeom",
        },
        {
          value: "asPoints",
          label: "asPoints",
        },
        {
          value: "asSpacedPoints",
          label: "asSpacedPoints",
        },
      ],
      drawType: "asGeom",
      activeShapeMesh: null,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    // 初始化
    init() {
      this.createScene(); // 创建场景
      this.createMesh(); // 创建网格模型
      this.createLight(); // 创建光源
      this.createCamera(); // 创建相机
      this.createRender(); // 创建渲染器
      this.createControls(); // 创建控件对象
      this.render(); // 渲染
      console.log(this.drawShape());
    },
    // 创建场景
    createScene() {
      scene = new THREE.Scene();
      //用于简单模拟3个坐标轴的对象.
      //红色代表 X 轴. 绿色代表 Y 轴. 蓝色代表 Z 轴.
      scene.add(new THREE.AxesHelper(20));
    },
    drawShape() {
      // 创建基础形状
      const shape = new THREE.Shape();

      // 设置起始点
      shape.moveTo(-10, 0);

      // 画线到新坐标
      shape.lineTo(-10, 30);

      // 贝塞尔曲线
      shape.bezierCurveTo(-5, 20, 5, 20, 10, 30);

      shape.lineTo(10, 0);

      // 样条曲线
      // shape.splineThru([
      //   new THREE.Vector2(32, 30),
      //   new THREE.Vector2(28, 20),
      //   new THREE.Vector2(30, 10),
      // ]);

      // 底部二次曲线
      // shape.quadraticCurveTo(20, 15, 10, 10);

      // 左眼
      const hole1 = new THREE.Path();
      hole1.absellipse(-5, 18, 2.3, 0.7, 0, Math.PI * 2, true);
      shape.holes.push(hole1);

      // 右眼
      const hole2 = new THREE.Path();
      hole2.absellipse(5, 18, 2.3, 0.7, 0, Math.PI * 2, true);
      shape.holes.push(hole2);

      // 鼻子
      const hole3 = new THREE.Path();
      hole3.moveTo(0, 14);
      hole3.lineTo(1, 12);
      hole3.lineTo(-1, 12);
      shape.holes.push(hole3);

      // 嘴巴
      const hole4 = new THREE.Path();
      hole4.absellipse(0, 6, 5, 1, 0, Math.PI * 2, true);
      shape.holes.push(hole4);

      shape.lineTo(-10, 0);

      return shape;
    },
    // 创建网格模型
    createMesh() {
      // 创建二维几何体
      const geom = new THREE.ShapeGeometry(this.drawShape());

      const pM = new THREE.MeshPhongMaterial({
        color: 0x111111,
        side: THREE.DoubleSide,
      });
      this.activeShapeMesh = new THREE.Mesh(geom, pM);
      this.activeShapeMesh.position.set(0, -10, 0);
      // 平面对象添加到场景中
      scene.add(this.activeShapeMesh);
    },

    // 创建光源
    createLight() {
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.1); // 创建环境光
      scene.add(ambientLight); // 将环境光添加到场景

      const spotLight = new THREE.PointLight(0xffffff); // 创建聚光灯
      spotLight.position.set(0, 10, 20);
      spotLight.castShadow = true;
      scene.add(spotLight);
    },
    // 创建相机
    createCamera() {
      const element = document.getElementById("scene");
      const k = element.clientWidth / element.clientHeight; // 窗口宽高比
      // PerspectiveCamera( fov, aspect, near, far )
      camera = new THREE.PerspectiveCamera(35, k, 0.1, 1000);
      camera.position.set(0, 0, 80); // 设置相机位置

      camera.lookAt(new THREE.Vector3(10, 0, 0)); // 设置相机方向
      scene.add(camera);
    },
    // 创建渲染器
    createRender() {
      const element = document.getElementById("scene");
      renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
      renderer.setSize(element.clientWidth, element.clientHeight); // 设置渲染区域尺寸
      renderer.shadowMap.enabled = true; // 显示阴影
      renderer.shadowMap.type = THREE.PCFSoftShadowMap;
      renderer.setClearColor(0x3f3f3f, 1); // 设置背景颜色
      element.appendChild(renderer.domElement);
    },

    // 更新属性
    updateFun() {
      scene.remove(this.activeShapeMesh);

      if (this.drawType === "asGeom") {
        this.createMesh();
      } else {
        let points = [];
        if (this.drawType === "asPoints") {
          points = this.drawShape().getPoints(10); // 从shape路径的每一个部分返回10个点
        } else if (this.drawType === "asSpacedPoints") {
          points = this.drawShape().getSpacedPoints(10); // 从整个shape路径返回10个点
        }
        const shapeGeometry = new THREE.BufferGeometry().setFromPoints(points);
        // new THREE.Line 同new THREE.Mesh一样创建的是网格对象 需要两个参数：geometry几何对象和material材质对象
        this.activeShapeMesh = new THREE.Line(
          shapeGeometry,
          new THREE.LineBasicMaterial({
            color: 0xff3333,
            linewidth: 1,
          })
        );
        this.activeShapeMesh.position.set(0, -10, 0);
        scene.add(this.activeShapeMesh);
      }
    },
    render() {
      this.updateFun();
      renderer.render(scene, camera);
      requestAnimationFrame(this.render);
    },
    // 创建控件对象
    createControls() {
      controls = new OrbitControls(camera, renderer.domElement);
    },
  },
};
</script>
<style>
.shape-geometry {
  width: 100%;
  height: 100%;
  position: relative;
}
#scene {
  width: 100%;
  height: 100%;
}
.controls-box {
  position: absolute;
  right: 5px;
  top: 5px;
  width: 300px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #c3c3c3;
}
.label-col {
  padding: 8px 5px;
}
</style>

